package com.qfedu.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.qfedu.recommend.RecommendAPI;
import com.qfedu.service.OrderService;
import com.qfedu.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者：刘随阳
 * 时间: 2021/9/25 10:37
 * 描述：神光照耀,太白成瑞。六丙来迎,百福悠归
 */
@RestController
@RefreshScope
@RequestMapping("wx")
public class WxController {

    @Autowired
    private RecommendAPI recommendAPI;

    @Autowired
    private OrderService orderService;

    @RequestMapping("/callback")
    public String callback(HttpServletRequest req) throws Exception {
        //微信的返回值是xml格式 先将结果以String格式取出来
        ServletInputStream inputStream = req.getInputStream();
        StringBuilder str = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(bytes)) != -1){
            String s = new String(bytes,0,len);
            str.append(s);
        }
        String s = str.toString();

        //再将String格式转为Map集合
        Map<String, String> resultMap = WXPayUtil.xmlToMap(s);
        if(resultMap != null && "SUCCESS".equalsIgnoreCase(resultMap.get("return_code"))){
            String orderId = resultMap.get("out_trade_no");
            WebSocketServer.sendmsg(orderId,"1");
            //4.当订单状态修改完成之后，对微信支付平台进行响应
            boolean b = orderService.updateOrder(orderId);
            System.out.println("-------------微信支付回调接口："+orderId+",状态："+b);
            //（如果成功响应微信支付平台，微信支付平台就不在重复发送当前订单的支付结果）
            Map<String, String> respMap = new HashMap<>();
            respMap.put("return_code","success");
            respMap.put("result_code","success");
            respMap.put("return_msg","OK");
            respMap.put("appid",resultMap.get("appid"));
            return WXPayUtil.mapToXml(respMap);
        }
        System.out.println("callback");
        return null;
    }
}
